/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.maze.behaviours;

import org.maze.individual.Individual;
import org.maze.utils.Vector;

/**
 *
 * @author Thomas
 */
public class RemoveLoopImprovementBehaviour extends AbstractImprovementBehaviour implements IImprovementBehaviour{

    public byte[] improve(Individual individual) {
        byte[] newGenome = individual.getGenome().clone();
        for(int i=0; i < newGenome.length; i++){
            Vector vector = new Vector();
            byte val = newGenome[i];
            if(val == Individual.EAST)
                vector.x+=1;
            else if(val == Individual.WEST)
                vector.x-=1;
            else if(val == Individual.NORTH)
                vector.y-=1;
            else if(val == Individual.SOUTH)
                vector.y+=1;
            for(int j=i+1; j < newGenome.length; j++){
                val = newGenome[j];
                if(val == Individual.EAST)
                    vector.x+=1;
                else if(val == Individual.WEST)
                    vector.x-=1;
                else if(val == Individual.NORTH)
                    vector.y-=1;
                else if(val == Individual.SOUTH)
                    vector.y+=1;
                byte[] element = new byte[1];
                try{
                    if(vector.x == 1 && vector.y == 0){
                        element[0]=Individual.EAST;
                        newGenome = this.replace(newGenome, i, j-i, element);
                        return newGenome;
                    }else if(vector.x == -1 && vector.y == 0){
                        element[0]=Individual.WEST;
                        newGenome = this.replace(newGenome, i, j-i, element);
                        return newGenome;
                    }else if(vector.x == 0 && vector.y == 1){
                        element[0]=Individual.SOUTH;
                        newGenome = this.replace(newGenome, i, j-i, element);
                        return newGenome;
                    }else if(vector.x == 0 && vector.y == -1){
                        element[0]=Individual.NORTH;
                        newGenome = this.replace(newGenome, i, j-i, element);
                        return newGenome;
                    }
                }catch(Exception e){
                    System.out.println(e.getMessage());
                    System.exit(-1);
                }
            }
        }
        return individual.getGenome();
    }

}
